<?php
/**
 * 2017年3月16日
 */
class MY_Controller extends CI_Controller {

    function __construct(){
        parent::__construct();
        /*开启Session*/
        @session_start();
        ob_start();
        // date_default_timezone_set('PRC');
        // 图片基础参数设置
        // 字符编码
        $this->load->helper('url');
        header ('Content-Type: text/html; charset=UTF-8');
        date_default_timezone_set('Asia/Shanghai');
        ini_set('memory_limit','256M');
        
        define('IS_GET', $_SERVER['REQUEST_METHOD'] == 'GET' ? true : false);
        define('IS_POST', $_SERVER['REQUEST_METHOD'] == 'POST' ? true : false);
        define('LINES', '8');
        define('AGENTSGOODSLINES', '5');
        define('AGENTSBALANCELINES', '5');
        define('HW_JS',base_url().'static/js/');
        define('HW_CSS',base_url().'static/css/');
        define('HW_IMG',base_url().'static/img/');

        define('HW_AdminLTE',base_url().'static/admin-lte/');
    }

    function trans_rollback($msg = '操作失败')
    {
        $this->db->trans_rollback();
        return array('code'=>0,'msg'=>$msg);
    }

    function trans_commit($msg = '操作成功')
    {
        $this->db->trans_commit();
        return array('code'=>1,'msg'=>$msg);
    }

    /**
     * 获取编码
     * @param  [type] $str [description]
     * @return [type]      [description]
     */
    function get_code($str)
    {
        return $str.date('ymdhis', time()).rand(0, 9).rand(0, 9);
    }

    /**
     * 后台列表筛选信息渲染
     * @param  [type] $get [description]
     * @return [type]      [description]
     */
    function get_array($info,$pages=1,$get=array())
    {
            $count_page = isset($info['count']) && $info['count']?ceil($info['count']/LINES):1;
            $data['pageSize'] = LINES;
            $data['pageNum'] = $pages?$pages:1;
            $data['pages'] = $pages?$pages:1;
            if($count_page == 1){
                $data['navigatepageNums'] = array(1);
            }elseif($count_page <= 5){
                for($i=1;$i<=$count_page;$i++){
                    $data['navigatepageNums'][] = $i;
                }
            }elseif($pages+3 > $count_page){
                for($i=$count_page-4;$i<=$count_page;$i++){
                    $data['navigatepageNums'][] = $i;
                }
            }else{
                if($pages<3){
                    for($i=1;$i<=5;$i++){
                        $data['navigatepageNums'][] = $i;
                    }
                }else{
                    for($i=$pages-2;$i<=$pages+2;$i++){
                        $data['navigatepageNums'][] = $i;
                    }
                }
            }
            // $data['navigatepageNums'] = isset($info['navigatepageNums'])?$info['navigatepageNums']:array(1);
            $data['hasPreviousPage'] = $pages > 1?true:false;
            $data['hasNextPage'] = $pages<$count_page?true:false;
            $data['prePage'] = $pages>1?$pages-1:0;
            $data['nextPage'] = $pages<$count_page?$pages+1:0;;
            $data['lastPage'] = $count_page?$count_page:1;
            $data['total'] = isset($info['count'])?$info['count']:0;
            $data['url'] = 'https://'.$_SERVER['HTTP_HOST'].'/'.$this->uri->segment(1).'/'.$this->uri->segment(2).'/'.$this->uri->segment(3).'/';
            $data['get'] = $_SERVER['QUERY_STRING'];
            $data['list'] = isset($info['list'])?$info['list']:'';
            if (!empty($get)) {
                foreach ($get as $key => $value) {
                    $data[$key] = $value;
                }
            }
            return $data;
    }

    /**
     * 检验签名
     */
    function checkSignature($param){
        if(!isset($param['Uid'])||!isset($param['signature'])){
            return false;
        }else{
            if(strcmp($param['signature'], md5($param['Uid'].date('Ymd')))==0){
                return true;
            }else{
                return false;
            }
        }
    }
    /**
     * 自定义操作成功页面 默认跳转操作前一个页面
     * @return [type] [description]
     */
    function success($info='',$jumpUrl='',$waitsecond=1)
    {
        if($jumpUrl==''){
            $jumpUrl = $_SERVER["HTTP_REFERER"];
        }
        $data = array(
            'info'=>$info,
            'jumpUrl'=>$jumpUrl,
            'waitsecond'=>$waitsecond,
            'status'=>1,         //表示成功操作
            'firstloc'=>'操作结果',
            'secondloc'=>'操作成功',
        );
        $this->load->view('public/message',$data);
    }
    /*
     * 自定义操作失败页面
     * @param  string  $info       [提示信息]
     * @param  [type]  $jumpUrl    [跳转地址]
     * @param  integer $waitsecond [等待时间]
     * @return [type]              [description]
     */
    function error($info='',$jumpUrl='',$waitsecond=2){
        if($jumpUrl==''){
            $jumpUrl = $_SERVER["HTTP_REFERER"];
        }
        $data = array(
            'info'=>$info,
            'jumpUrl'=>$jumpUrl,
            'waitsecond'=>$waitsecond,
            'status'=>0,        //表示失败操作
            'firstloc'=>'操作结果',
            'secondloc'=>'操作失败',
        );
        $this->load->view('public/message',$data);
    }

    /**
     * [无权限页面跳转]
     * @AuthorHTL
     * @DateTime  2017-08-15T11:49:53+0800
     * @param     [type] $msg [权限跳转提示]
     */
    function autherror($msg = '您无权限进行该操作')
    {
        $data['msg'] = $msg;
        $this->load->view('Public/authority', $data);
    }

    /**
     * 处理操作结果
     * @param  [type] $result [description]
     * @return [type]         [description]
     */
    function handleResult($result,$url = ''){
        if($result['code']==1){
            $this->success($result['msg'],$url);
        }else{
            $this->error($result['msg'],$url);
        }
    }

    /**
     * 正则匹配要访问的访问需要控制的权限
     * @return [type] [description]
     */
    function matchMethod($func)
    {
        // 权限控制 获取要访问的方法名 并对该方法进行正则匹配
        if (preg_match('/List|list/', $func))
        {
            $method = 'select';    
        }
        else if (preg_match('/add|Add|Insert|insert/', $func))
        {
            $method = 'add';
        }
        else if (preg_match('/edit|Edit|update|change|Update|Change/', $func))
        {
            $method = 'edit';
        }
        else if (preg_match('/del|Del|delete|Delete|cancel|Cancel/', $func))
        {
            $method = 'del';
        }
        else
        {
            $method = '';
        }

        return $method;
    }

    /*
    权限验证
    $action[模块名] $method【具体请求的方法,只有3个值 add，edit，del，select，reviewed，all】 $usergroup【用户权限组，取表的usergroup字段】
    例如：用户编辑权限判断时如下调用：
    $this->authcheck('User','edit','23');
    2017.3.27 小黑鼠
    */
    function authcheck($action, $method, $usergroup=0){
        // return true;

        $this->load->model('AuthManager/Auth_model','auth');
        //若无权限列表则根据登陆用户session去取权限组的权限
        if(!isset($_SESSION['authgroup'])){
            $_SESSION['authgroup'] = $this->auth->getsessionauth($_SESSION['admin_info']['usergroup']);
        }
        //若无需检测的权限列表则加载该列表
        // unset($_SESSION['authlist']);
        if(!isset($_SESSION['authlist'])){
            $res = $this->auth->getsessionauthname($_SESSION['admin_info']['shop_token']);
            foreach ($res as $key => $value) {
                $authlist[]=$value['authname'];
            }  
            $_SESSION['authlist']= $authlist;
        }


        if(!in_array($action, $_SESSION['authlist'])){
            return true;
        }
        //若请求的模块在用户所在权限组里，进行进一步判断
        if(in_array($action, array_keys($_SESSION['authgroup']))){
            if(in_array($method, $_SESSION['authgroup'][$action])){
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }


    /**
     * 获取分页数据
     * @param    [type]     $info [数据列表]
     * @param    [type]     $page [页数]
     * @param    [type]     $url  [方法地址]
     * @param    [type]     $get  [$_GET数据]
     * @return   [type]           [description]
     */
    function getPage($info,$url,$pages=1,$get=array(),$lines=LINES){
        // $count_page = isset($info['count']) && $info['count']?ceil($info['count']/LINES):1;
        // $data['pageSize'] = LINES;
        $count_page = isset($info['count']) && $info['count']?ceil($info['count']/$lines):1;
        $data['pageSize'] = $lines;
        $data['pageNum'] = $pages?$pages:1;
        $data['pages'] = $pages?$pages:1;
        if($count_page == 1){
            $data['navigatepageNums'] = array(1);
        }elseif($count_page <= 5){
            for($i=1;$i<=$count_page;$i++){
                $data['navigatepageNums'][] = $i;
            }
        }elseif($pages+3 > $count_page){
            for($i=$count_page-4;$i<=$count_page;$i++){
                $data['navigatepageNums'][] = $i;
            }
        }else{
            if($pages<3){
                for($i=1;$i<=5;$i++){
                    $data['navigatepageNums'][] = $i;
                }
            }else{
                for($i=$pages-2;$i<=$pages+2;$i++){
                    $data['navigatepageNums'][] = $i;
                }
            }
        }
        // $data['navigatepageNums'] = isset($info['navigatepageNums'])?$info['navigatepageNums']:array(1);
        $data['hasPreviousPage'] = $pages > 1?true:false;
        $data['hasNextPage'] = $pages<$count_page?true:false;
        $data['prePage'] = $pages>1?$pages-1:0;
        $data['nextPage'] = $pages<$count_page?$pages+1:0;;
        $data['lastPage'] = $count_page?$count_page:1;
        $data['total'] = isset($info['count'])?$info['count']:0;
        $data['url'] = base_url().$url;
        $data['get'] = $_SERVER['QUERY_STRING'];
        $data['list'] = isset($info['list'])?$info['list']:'';
        if (!empty($get)) {
            foreach ($get as $key => $value) {
                $data[$key] = $value;
            }
        }
        return $data;
    }


    /**
     * [验证当前用户是否有访问权限]
     * @Author   ysm
     * @DateTime 2018-08-19
     * @param    [type]     $fun [当前控制器地址]
     * @return   [type]          [description]
     */
    function checkAuth($fun){
        //获取当前权限id
        $res = $this->db->where('controller',$fun)->get('group_permission')->row_array();
        if(!$res||$res['del_status'] == 1){
            return array('code'=>1,'message'=>'允许访问');
        }
        $id = $_SESSION['admin_info']['id'];
        //获取当前用户角色
        $result = $this->db->select('usergroup,id')->where('id',$id)->get('admin')->row_array();
        $usergroup = explode(',', $result['usergroup']); 
        //获取当前用户所拥有权限id
        $info = $this->db->select('id,authority_id')->where_in('id',$usergroup)->get('group_character')->result_array();
        $authority = '';
        foreach ($info as $key => $value) {
            $authority .= ','.$value["authority_id"];
        }
        $arr = explode(',', $authority); 

        if (!in_array($res, $arr)) { //判断前用户所拥有权限id 是否存在当前控制器id
            return array('code'=>402,'message'=>'无访问权限');
        }

    }

}

    /**
     * 管理员
     */
    class Admin_Controller extends MY_Controller
    {
        /**
         * 权限检查
         * @param  [type] $class [description]
         * @return [type]        [description]
         */
        // function auth_check($class)
        // {

        //         //获取用户权限
        //         // $authority = explode(',', $_SESSION['supplier_admin_info']['authority']);
        //         //  //判断用户是否有访问控制器的权限
        //         // if(!in_array($class, $authority)){
        //         //     return false;
        //         // }else{
        //         //     return true;
        //         // }
        // }
        function __construct()
        {
            parent::__construct();

            if (!isset($_SESSION['admin_info'])){

                if (Common::isAjax())
                {
                    echo json_encode(array('code'=>0,'msg'=>'您长时间未操作系统，请重新登录'));
                    exit();
                }
                else
                {
                    //跳转回商家管理员登入界面
                    echo "<script>window.alert('您的登录已失效， 请重新登录'); window.top.location.href = '".base_url()."Admin/Login/login';"."</script>";
                    exit();

                }
            }
            
            // var_dump($_SESSION['admin_info']['controller']);  //用户持有权限控制器
            // var_dump($_SERVER['REDIRECT_URL']);               //当前操作方法
            //判断当前用户是否有操作权限
            $key = trim($_SERVER['REQUEST_URI'],'/');        
            //判断当前方法是否设置权限
            $res = $this->db->select('*')->where(array('del_status' => 0,'controller' => $key))->from('group_permission')->get()->row_array(); 
            if($res){
                //存在该权限
                if(!in_array($key, $_SESSION['admin_info']['controller'])){
                    //用户
                    if($res['status'] == 1){
                        //a链接 跳转中间页
                        // $this->load->view();
                    }else{
                        //ajax
                        $re = array(
                            'code' =>402,
                            'msg' =>'无访问权限'
                        );
                        // echo json_encode($re);return;
                    }
                }
            }else{
                //不存在该权限
                // echo '111';
            }               
        }

        
    }
    /**
     * 微信父类
     */
    class Weixin_Controller extends MY_Controller
    {

        function __construct()
        {
            parent::__construct();

            // $_SESSION['userinfo'] = $this->db->select('*')->get('agents')->row_array();
            // $_SESSION['userinfo'] = $this->db->select('*')->where(array('id'=>'2'))->get('agents')->row_array();
            
            if (!isset($_SESSION['userinfo'])){
                if (Common::isAjax())
                {
                    echo json_encode(array('code'=>0,'msg'=>'您长时间未操作系统，请重新登录'));
                    exit();
                }
                else
                {
                    // $_SESSION['shop_token'] = 'abcdefg12345';
                    $_SESSION['redirect_url'] = base_url().$_SERVER["REQUEST_URI"];
                    //跳转回微信登入界面
                    redirect(base_url().'Weixin/Login/login');
                }
            }else{
                $agent_id=isset($_SESSION['userinfo']['id'])?$_SESSION['userinfo']['id']:'';
                $agentStatus=$this->db->select('status')->where(array('id'=>$agent_id))->get('agents')->row_array();
                if(isset($agentStatus['status'])&&($agentStatus['status']=='1')){
                    echo '账号已被冻结！';
                    if(isset($_SESSION['userinfo']))unset($_SESSION['userinfo']);
                    exit();
                }
            }

        }
    }
    /**
     * App父类
     */
    class App_Controller extends MY_Controller
    {
        function __construct()
        {
            parent::__construct();

            // 账号冻结后，不可登录代理前台，推荐奖、共享奖、货款分成不计算，原团队关系保持；
            // $_SESSION['userinfo']=$this->db->select('*')->get('agents')->row_array();

            $agent_id=isset($_SESSION['userinfo']['id'])?$_SESSION['userinfo']['id']:'';
            $agentStatus=$this->db->select('status')->where(array('id'=>$agent_id))->get('agents')->row_array();
            if(isset($agentStatus['status'])&&($agentStatus['status']=='1')){
                echo '账号已被冻结！';
                if(isset($_SESSION['userinfo']))unset($_SESSION['userinfo']);
                exit();
            }


            // $this->load->model('App/User_model','user');
            // if(isset($_SESSION['userinfo'])){
            //     if(date('Y-m-d',strtotime($_SESSION['userinfo']['last_login_time'])) != date('Y-m-d')){
            //         $_SESSION['userinfo']['last_login_time'] = date('Y-m-d H:i:s');
            //         $this->load->model('App/User_model','user');
            //         $this->user->setPointRecord($_SESSION['userinfo']['id'],2);
            //     }
            // }
            // if (!isset($_SESSION['userinfo'])){
            //     if (Common::isAjax())
            //     {
            //         echo json_encode(array('code'=>0,'msg'=>'您长时间未操作系统，请重新登录'));
            //         exit();
            //     }
            //     else
            //     {
            //         echo "<script>window.alert('您的登录已失效， 请重新登录'); window.top.location.href = '".base_url()."App/Login/index';"."</script>";
            //         exit();
            //     }
            // }            
        }
    }